package com.woniuxy.service.impl;


import com.woniuxy.config.RabbitConfig;
import com.woniuxy.litener.FlushToDBListener;
import com.woniuxy.service.LogFlushService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class LogFlushServiceImpl implements LogFlushService {

    // Redis 中存储日志的列表 key
    private static final String LOG_LIST_KEY = "log:list";

    // 每次批量刷库的最大日志数量
    private static final Long BATCH_SIZE = 5L;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private FlushToDBListener flushToDBListener;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public void flushLogs() {



        RLock lock = redissonClient.getLock("log:flush:lock");

        Boolean isLocked = false;

        try {
            //尝试获取锁，最多等待2秒，锁自动释放时间为10 秒
            isLocked = lock.tryLock(2,10, TimeUnit.SECONDS);
            if(isLocked) {
                Long size = redisTemplate.opsForList().size(LOG_LIST_KEY);

                if (size == null || size == 0) return;
                while (size >= BATCH_SIZE){
                    List<Object> logs = redisTemplate.opsForList()
                                            .range(LOG_LIST_KEY, -BATCH_SIZE,-1 );

                    if(logs ==null || logs.isEmpty()) break;

                    //调用mq监听器将缓存刷入数据库中
                    rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_NAME,RabbitConfig.ROUTING_KEY_DB,logs);

                    //左保留除删掉之外的元素
                    redisTemplate.opsForList().trim(LOG_LIST_KEY, 0, -BATCH_SIZE-1);
//                    重新获取长度，
                    size = redisTemplate.opsForList().size(LOG_LIST_KEY);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //  确保当前线程释放锁（防止死锁）
            if(isLocked && lock.isHeldByCurrentThread()) lock.unlock();
        }


    }
}
